import json
import random
import time
import traceback

from bilibili_api import video, sync, comment, Credential
from user_agent import generate_user_agent

from sam.util.httpUtil import http_get
from sam.util.strUtil import filter_symbol_4_word
from sam.wrapper.CommonWrapper import catch_and_print_exception

credential2 = Credential(
    sessdata="cceedcf0%2C1643598167%2C37501%2A81"
    , bili_jct="f781ea758fb5309a162ea1173174e847"
    , buvid3="73E04E99-69AC-492F-9EF6-B7CBAE2BE34A58494infoc"
)

credential = Credential(
    # 大王卡
    sessdata="ead57fb4%2C1643617765%2Cc0505*81"
    , bili_jct="c1924b3ef8e0d6b370acf42b9efb1fc0"
    , buvid3="73E04E99-69AC-492F-9EF6-B7CBAE2BE34A58494infoc"
)

cookies = credential.get_cookies()
agent = generate_user_agent()


@catch_and_print_exception
async def comment_async(aid: int):
    # 存储评论
    comments = []
    # 页码
    page = 1
    # 当前已获取数量
    count = 0
    while True:
        time.sleep(1)
        # 获取评论
        c = await comment.get_comments(
            oid=aid
            , type_=comment.ResourceType.VIDEO
            , page_index=page
            , credential=credential
        )
        # 存储评论
        comments.extend(c['replies'])
        # 增加已获取数量
        count += c['page']['size']
        # 增加页码
        page += 1
        if count >= c['page']['count']:
            # 当前已获取数量已达到评论总数，跳出循环
            break

    # 打印评论
    # for cmt in comments:
    #     print(f"{cmt['member']['uname']}: {cmt['content']['message']}")

    # 打印评论总数
    # print(f"\n\n共有 {count} 条评论（不含子评论）")

    comment_text = ' '.join(
        [filter_symbol_4_word(cmt['content']['message'], is_need_filter_start_end=True) for cmt in comments])
    return count, comment_text


def comment_sync2(aid: int):
    try:
        return sync(comment_async(aid))
    except:
        traceback.print_exc()
        print(f"获取评论异常, aid:  {aid}")
        return 0, ""


def comment_sync(aid: int):
    # 存储评论
    comments = []
    # 页码
    page = 1
    # 当前已获取数量
    count = 0
    while True:
        time.sleep(random.randint(1, 10) / 10)
        comment_url = f"https://api.bilibili.com/x/v2/reply?pn={page}&type=1&oid={aid}&sort=0"
        header = {"User-Agent": agent, "Referer": comment_url}
        response = http_get(url=comment_url, header=header, cookies=cookies)
        c = json.loads(response.text)['data']
        # 存储评论
        comments.extend(c['replies'])
        # 增加已获取数量
        count += c['page']['size']
        # 增加页码
        page += 1
        if count >= c['page']['count']:
            # 当前已获取数量已达到评论总数，跳出循环
            break

    # 打印评论
    # for cmt in comments:
    #     print(f"{cmt['member']['uname']}: {cmt['content']['message']}")

    # 打印评论总数
    # print(f"\n\n共有 {count} 条评论（不含子评论）")

    comment_text = ' '.join(
        [filter_symbol_4_word(cmt['content']['message'], is_need_filter_start_end=True) for cmt in comments if
         cmt['content']['message']])
    return count, comment_text


def dm_sync(v: video):
    try:
        dms = sync(v.get_danmakus(0))
        dm_text = ' '.join([filter_symbol_4_word(dm.text, is_need_filter_start_end=True) for dm in dms])
        dm_num = len(dms)
        return dm_num, dm_text
    except:
        traceback.print_exc()
        print(f"获取弹幕异常, bvid: {v.get_bvid()}")
        return 0, ""


@catch_and_print_exception
def get_video_detail(bvid: str):
    v = video.Video(bvid=bvid, credential=credential)
    # time.sleep(2)
    # stat = sync(v.get_stat())
    # time.sleep(2)
    # dm_num, dm_text = dm_sync(v)
    # time.sleep(2)
    comment_num, comment_text = comment_sync(v.get_aid())
    return {
        "uuid": bvid
        # , "watch_num": stat['view']
        # , "like_num": stat['like']
        # , "coin_num": stat['coin']
        # , "collect_num": stat['favorite']
        # , "share_num": stat['share']
        # , "dm_num": dm_num
        # , "dm_text": dm_text
        , "comment_num": comment_num
        , "comment_text": comment_text
    }


if __name__ == "__main__":
    detail = get_video_detail('BV1st4y197Fx')
    print(detail)
